<!--
  文件描述：选择用户组件
-->
<template>
  <div>
    <div @click.capture="openDialog" :style="{width}">
      <el-input-tag
          :placeholder="placeholder"
          v-model="selectShow"
          v-bind="$attrs"
          :max="max"
          :style="{width}"
          :suffix-icon="suffixIcon"
      ></el-input-tag>
    </div>

    <el-dialog
     v-model="dialog.open"
     :title="dialogTile"
     :before-close="close"
     style="width: 60%"
    >
      <div :class="$isMobile() ? 'content-box-wap' : 'content-box'">
        <div :class="[`${$isMobile() ? 'item-width' : ''}`, 'content-item', 'border']">
          <div style="font-size: 16px;font-weight: 600;margin-bottom: 10px">部门列表</div>
          <el-input
            clearable
            v-model="dialog.deptName"
            style="width: 80%"
            placeholder="请输入部门名称查询"
            @blur="getDeptTreeData" />
          <div style="height: 390px;overflow-y: auto;">
            <el-tree
              :data="deptTreeData"
              :expand-on-click-node="false"
              default-expand-all
              :props="{
                        children: 'children',
                        label: 'deptName',
                        value: 'deptId'
                    }"
              @node-click="selectDept"
              v-loading="dialog.loading"
              element-loading-text="数据加载中..." />
          </div>
        </div>
        <div
            class="content-item"
            :style="$isMobile() ? {width: '100%', padding: '0', marginBottom: '10px'} : {width: '50%', padding: '0'}"
        >
          <el-form
              inline
              class="border"
              :model="form"
              label-width="auto"
              style="padding: 10px;margin-bottom: 5px;"
          >
            <el-form-item style="width: 39%">
              <el-input clearable v-model="form.username"  placeholder="请输入用户名查询" />
            </el-form-item>
<!--            <el-form-item>-->
<!--              <el-input clearable v-model="form.phone" style="width: 200px" placeholder="请输入手机号查询" />-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" @click="getData" icon="Search">查询</el-button>
              <el-button @click="reset" icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-table
                border
                :height="380"
                empty-text="暂无数据"
                :show-overflow-tooltip="true"
                :data="tableData"
                v-loading="dialog.loadingList"
                element-loading-text="数据加载中..."
                :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }"
            >
              <el-table-column prop="userNo" label="用户账号" />
              <el-table-column prop="username" label="用户名称" />
              <el-table-column prop="phone" show-overflow-tooltip min-width="120" label="手机号码" />
              <el-table-column fixed="right" label="操作" width="100">
                <template v-slot="{row}">
                  <el-button
                      type="primary"
                      size="small"
                      icon="CirclePlus"
                      @click="addUser(row)"
                  >添加</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="page.currentPage"
                v-model:page-size="page.pageSize"
                style="margin-top: 8px;"
                size="small"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, prev, pager, next"
                :background="!$isMobile()"
                :total="page.total"
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <div :class="[`${$isMobile() ? 'item-width' : ''}`, 'content-item', 'border']">
          <div>
            <div class="content-box" style="align-items: center;">
              <p>已选择: {{ select.length }}</p>
              <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                  @click="del('all')"
              >删除全部</el-button>
            </div>
            <el-table
                border
                :height="400"
                empty-text="暂无数据"
                :show-overflow-tooltip="true"
                :data="select"
                element-loading-text="数据加载中..."
                :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }"
            >
              <el-table-column prop="username" label="用户名称" />
              <el-table-column fixed="right" label="操作">
                <template v-slot="{ row }">
                  <el-button
                      type="primary"
                      size="small"
                      icon="Delete"
                      @click="del('', row.userId)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="userSelect">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api';
const props = defineProps({
  userIds: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择用户'
  },
  width: {
    type: String,
    default: '200px'
  },
  suffixIcon: {
    type: String,
    default: 'Plus'
  },
  max: {
    type: Number,
    default: 1
  },
  dialogTile: {
    type: String,
    default: '用户选择'
  },
})

const select = ref([]) // 操作之中的选择项
const haveSelect = ref([]) // 确定的选择项
const selectShow = ref([]) // 确定的选择项名称
const dialog = ref({
  open: false,
  deptName: '',
  loading: false,
  deptId: '',
  loadingList: false
})
const deptTreeData = ref([])
const tableData = ref([])
const form = ref({
  username: '',
  phone: '',
  status: '0'
})
const emits = defineEmits(['submit', 'update:userIds'])
const page = ref({ pageSize: 10, pageNum: 1, currentPage: 0, total: 0, pagerCount: 4 })


// 打开弹窗
const openDialog = () => {
  dialog.value.open = true
  getDeptTreeData()
  getData()
  select.value = JSON.parse(JSON.stringify(haveSelect.value)) // 把已经选择展示在列表中
}

// 确定
const submit = () => {
  selectShow.value = select.value.map(v => v.username) || []
  haveSelect.value = select.value.map(v => v)
  emits('update:userIds', haveSelect.value.map(v => v.userId).join(','))
  emits('submit', {haveSelect: JSON.parse(JSON.stringify(haveSelect.value))})
  close()
}

// 关闭弹窗
const  close = () => {
  dialog.value.open = false
}


//获取部门树
const getDeptTreeData = async () => {
  dialog.value.loading = true
  const res = await api.get('/author/dept/treeData', {deptName: dialog.value.deptName})
  if (res.data.code === 200) {
    deptTreeData.value = res.data.data || []
  } else {
    ElMessage.error(res.data.msg)
  }
  dialog.value.loading = false
}

//选择部门
const selectDept = (data) => {
  form.value.deptId = data.deptId || ''
  getData()
}

//获取数据
const getData = async () => {
  dialog.value.loadingList = true
  let params = { pageNum: page.value.pageNum, pageSize: page.value.pageSize, ...form.value }
  const res = await api.get('/author/user/pageList', params)
  if (res.data.code === 200) {
    tableData.value = res.data.data.records || []
    page.value.currentPage = res.data.data.current
    page.value.total = res.data.data.total
  } else {
    ElMessage.error(res.data.msg)
  }
  dialog.value.loadingList = false
}

//切换页
const handleSizeChange = (val) => {
  page.value.pageSize = val
  getData()
}
const handleCurrentChange = (val) => {
  page.value.pageNum = val
  getData()
}

//重置查询条件
const reset = () => {
  form.value = {status: '0'}
  getData()
}

// 添加用户
const addUser = (row) => {
  // 单选
  const index = select.value.findIndex(v => v.userId === row.userId)
  if (index !== -1) return ElMessage.info('该数据已选择!')
  if (select.value.length === 1 && props.max === 1) {
    select.value = [{...row}]
  } else {
    if (props.max > select.value.length) {
      select.value.push(row)
    } else {
      ElMessage.info(`最多可选择${props.max}条`)
    }
  }
}
// 删除用户
const del = (type, id) => {
  if (type === 'all') {
    select.value = []
  } else  {
    const index = select.value.findIndex(v => v.userId === id)
    if (index !== -1) {
      select.value.splice(index, 1)
    }
  }
}

// 初始化
const init = async () => {
  let params = { status: '0', userIds: props.userIds }
  const res = await api.get('/author/user/pageList', params)
  if (res.data.code === 200) {
    haveSelect.value = res.data.data.records || []
    selectShow.value = haveSelect.value.map(v => v.username) || []
  } else {
    ElMessage.error(res.data.msg)
  }
}

onMounted(() => {
  if (props.userIds) {
    init()
  }
})

</script>
<style scoped lang="less">
.content-box-wap {
  display: flex;
  flex-wrap: wrap;
}
.content-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: nowrap;
}
.content-item {
  width: 20%;
  //height: 450px;
  padding: 10px;
}

.item-width {
  width: 100%;
  margin-bottom: 10px;
}

.border {
  border-shadow: 0 0 10px #f3f3f3;
  border-radius: 5px;
  border: 1px solid #e4e7ed;
}
.el-form--inline .el-form-item {
  margin-right: 2px;
}
</style>